package com.zyz.O_网络编程.TCP.Thread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: vick
 * @Date: 2025/4/15
 * @Description:
 * @version: 1.0
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //1. 创建ServerSocket对象，绑定8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待连接。。。。");
        int count = 0;
        //永远监听
        while (true) {
            //2. 监听客户端的连接， 这个方法是阻塞的，如果没有客户端连接会一致等待
            Socket socket = serverSocket.accept();
            count++;
            System.out.println("第" + count + "个客户端" + socket.getInetAddress().getHostAddress() + "连接成功");
            ClientHandleThread clientHandleThread = new ClientHandleThread(socket);
            clientHandleThread.start();
        }
    }

    static class ClientHandleThread extends Thread {
        private Socket socket;
        private String ip;

        public ClientHandleThread(Socket socket) {
            this.socket = socket;
            this.ip = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {

            try {
                //1. 获取输入流，接收客户端发送的数据
                InputStream inputStream = socket.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                //2. 获取输出流，发送数据给客户端
                OutputStream outputStream = socket.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                /*BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));*/

                String str;
                //3. 接收客户端发送的数据
                while ((str = bufferedReader.readLine()) != null) {
                    System.out.println(ip + "客户端发送的消息是：" + str);
                    //4. 反转
                    StringBuilder stringBuilder = new StringBuilder(str);
                    stringBuilder.reverse();

                    //5. 返回给客户端
                    printStream.println(stringBuilder.toString());
                    /*bufferedWriter.write(stringBuilder.toString());
                    bufferedWriter.newLine();
                    bufferedWriter.flush();*/
                }

                System.out.println("客户端" + ip + "正常退出");
            } catch (IOException e) {
                System.out.println("客户端" + ip + "异常退出");
            }finally {
                try {
                    //6. 关闭
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
